package com.mayikt.main.api.impl.producer;

import com.alibaba.fastjson.JSONObject;
import com.mayikt.main.constant.MQConstant;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author wangjin
 * @title: BatchDeliveryBuffer
 * @projectName mayikt-cloud
 * @description: TODO
 * @date 2022/5/14 0014 19:40
 */
@Component
@Slf4j
public class BatchDeliveryBuffer {
    /**
     * @Author wangjin
     * @Description //生产者对应缓冲区
     * @Date 2022/5/14 0014
     * @Param * @param null:
     * @return * @return: null
     **/
    private LinkedBlockingQueue<JSONObject> bufferQueue = new LinkedBlockingQueue<>();
    @Autowired
    private AmqpTemplate amqpTemplate;

    public BatchDeliveryBuffer() {
        new BatchBufferTHead().start();
    }

    public void addBuffer(JSONObject data) {
        //存入数据
        bufferQueue.offer(data);
    }

    class BatchBufferTHead extends Thread {
        /**
         * @return void
         * @Author wangjin
         * @Description //定义临时变量
         * @Date 2022/5/14 0014
         * @Param []
         **/
        @SneakyThrows
        @Override
        public void run() {
            while (true) {
                if (bufferQueue.size() <= 0) {
                    Thread.sleep(20);
                    continue;
                }
                ArrayList<JSONObject> tempBuffer = new ArrayList<>();
                for (int i = 0; i < MQConstant.BUFFER_SIZE; i++) {
                    JSONObject msgObj = bufferQueue.poll();
                    tempBuffer.add(msgObj);
                }
                //缓冲区满了5条数据,合并成一条msg
                String msg = JSONObject.toJSONString(tempBuffer);
                tempBuffer = null;
                //生产者mq
                amqpTemplate.convertAndSend("/mayikt_ex", "", msg);

            }
        }
    }

}
